package com.chenjiaru.thread.lock;

import com.chenjiaru.thread.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CyclicBarrier;

@Slf4j
public class CyclicBarrierDemo {

    public static int index = 0;

    public static void main(String[] arr) {
        CyclicBarrier barrier = new CyclicBarrier(3);
        for (int i = 1; i <= 6; i++) {
            ThreadUtil.mySleep(500);
            new Player("玩家" + i, barrier).start();
        }
    }

}

@Slf4j
class Player extends Thread {

    private CyclicBarrier barrier;

    public Player(String name, CyclicBarrier barrier) {
        this.setName(name);
        this.barrier = barrier;
    }

    @Override
    public void run() {
        try {
            log.warn("{}已经准备，当前等待的玩家={}", getName(), barrier.getNumberWaiting() + 1);
            barrier.await();
            log.warn("{}组队成功，开始游戏", getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
